package com.sita.cfmoto.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sita.cfmoto.ErrorCode;
import com.sita.cfmoto.R;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.RestResponse;
import com.sita.cfmoto.rest.model.request.UserRegisterRequest;
import com.sita.cfmoto.rest.model.response.Reply;
import com.sita.cfmoto.utils.L;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Class RegisterActivity is for
 *
 * @author xiaodong on 15/3/2.
 */
public class ForgetActivity extends AppCompatActivity {

    @Bind(R.id.mobile)
    EditText mMobile;
    @Bind(R.id.password)
    EditText mPassword;
    @Bind(R.id.confirm_password)
    EditText mConfirmPassword;
    @Bind(R.id.btn_reset_password)
    Button mResetPassword;
    @Bind(R.id.checkcode)
    EditText mCheckCode;
    @Bind(R.id.button_resend_check_code)
    Button mBtnGetCheckCode;

    public static Intent newIntent(Context context) {
        return new Intent(context, ForgetActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);
        ButterKnife.bind(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        backToLogin();
    }

    @OnClick(R.id.btn_login)
    void clickBack() {
        backToLogin();
    }

    private void backToLogin() {
        startActivity(LoginActivity.newIntent());
        this.finish();
    }

    @OnClick(R.id.btn_reset_password)
    void clickResetPassword() {
        String mobile = mMobile.getText().toString();
        if (TextUtils.isEmpty(mobile) || !mobile.startsWith("1")) {
            mMobile.setError(getText(R.string.error_invalid_mobile));
            return;
        }
        String password = mPassword.getText().toString();
        if (TextUtils.isEmpty(password)) {
            mPassword.setError(getText(R.string.error_invalid_password));
            return;
        }
        String confirmPassword = mConfirmPassword.getText().toString();
        if (TextUtils.isEmpty(confirmPassword)) {
            mConfirmPassword.setError(getText(R.string.error_invalid_password));
            return;
        }
        if (!confirmPassword.equals(password)) {
            mConfirmPassword.setError(getString(R.string.error_mismatch_password));
            mConfirmPassword.requestFocus();
            return;
        }

        final MaterialDialog dialog = new MaterialDialog.Builder(this).title(R.string.forget_pass).content(R.string.reset_pass_wait)
                .progress(true, 15000)
                .build();
        dialog.show();

        UserRegisterRequest request = new UserRegisterRequest();
        request.mobile = mobile;
        request.password = password;
        request.smscode = mCheckCode.getText().toString();

        RestClient.getRestService().userModifyPassword(request, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200) {
                    if (restResponse.mErrorCode.equals("0") && restResponse.mData != null) {
                        resetSuccess(dialog);

                    } else {
                        resetFailed(dialog);
                    }
                } else {
                    resetFailed(dialog);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                if (dialog != null && !dialog.isCancelled()) {
                    dialog.dismiss();
                }
                try {
                    Reply reply = (Reply) error.getBodyAs(Reply.class);
                    if (reply != null) {
                        if (reply.errorCode.equals(ErrorCode.MOBILE_NOT_EXIST)) {
                            Toast.makeText(ForgetActivity.this, getString(R.string.not_found_mobile), Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ForgetActivity.this, getString(R.string.error_reset_password), Toast.LENGTH_LONG).show();
                        }
                    }
                } catch (Exception e) {

                }
            }
        });

    }

    private void resetSuccess(MaterialDialog dialog) {
        if (dialog != null && !dialog.isCancelled()) {
            dialog.dismiss();
        }
        startActivity(new Intent(ForgetActivity.this, LoginActivity.class));
        ForgetActivity.this.finish();
    }

    private void resetFailed(MaterialDialog dialog) {
        if (dialog != null && !dialog.isCancelled()) {
            dialog.dismiss();
        }
    }

    @OnClick(R.id.button_resend_check_code)
    void onClickResendCheckCode() {
        if (fakeCheckCode())
            return;
        String mobile = mMobile.getText().toString();
        if (TextUtils.isEmpty(mobile) || mobile.length() < 11) {
            mMobile.setError(getText(R.string.error_invalid_mobile));
            mMobile.requestFocus();
            return;
        }
        if (mobile.length() > 11) {
            mobile = mobile.substring(0, 11);
            mMobile.setText(mobile);
            mMobile.requestFocus();
        }

        RestClient.getRestService().getCheckCode(mobile, new Callback<RestResponse>() {
                    @Override
                    public void success(RestResponse restResponse, Response response) {
                        if (response.getStatus() == 200) {
                            if (restResponse.mErrorCode.equals("0")) {
                            }
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        L.e(error);
                        try {
                            Reply reply = (Reply) error.getBodyAs(Reply.class);
                            if (reply != null) {
                                if (reply.errorCode.equals((ErrorCode.SMS_CODE_IS_UNLAW))) {
                                    Toast.makeText(ForgetActivity.this, getString(R.string.error_check_code_wrong), Toast.LENGTH_LONG).show();
                                } else if (reply.errorCode.equals(ErrorCode.MOBILE_EXIST)) {
                                    Toast.makeText(ForgetActivity.this, getString(R.string.duplicated_mobile), Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(ForgetActivity.this, getString(R.string.error_check_code_get), Toast.LENGTH_LONG).show();
                                }
                            }
                        } catch (Exception e) {
                            Toast.makeText(ForgetActivity.this, getString(R.string.error_check_code_get), Toast.LENGTH_LONG).show();
                        }
                    }
                }
        );


        new CountDownTimer(120 * 1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mBtnGetCheckCode.setEnabled(false);
                String item = getString(R.string.check_code_resend, millisUntilFinished / 1000 - 1);
                mBtnGetCheckCode.setText(item);
            }

            @Override
            public void onFinish() {
                mBtnGetCheckCode.setEnabled(true);
                mBtnGetCheckCode.setText(getString(R.string.check_code_get));
            }
        }.start();
    }

    boolean fakeCheckCode() {
        mCheckCode.setText("1234");
        return true;
    }
}
